<?php

namespace App\Log;

use EasySwoole\Trace\AbstractInterface\LoggerWriterInterface;

class LogHandler implements LoggerWriterInterface{

    public function writeLog($obj, $logCategory, $timeStamp){
        // TODO: Implement writeLog() method.
        $_obj = $this->isJson($obj);
        if($_obj === false){
            $content = date('Y-m-d H:i:s', $timeStamp)."\t".$obj.PHP_EOL;
        }else{
            $content = date('Y-m-d H:i:s', $timeStamp).PHP_EOL.var_export($_obj, true).PHP_EOL;
        }
        $filePrefix = $logCategory."_".date('Y-m-d');
        $filePath = EASYSWOOLE_ROOT."/Log/{$filePrefix}.log";
        file_put_contents($filePath, $content,FILE_APPEND|LOCK_EX);
    }

    /**
     * 判断字符串是否为 Json 格式
     * @param  string     $data  Json 字符串
     * @param  bool       $assoc 是否返回关联数组。默认返回对象
     * @return bool|array 成功返回转换后的对象或数组，失败返回 false
     */
    public function isJson($data = '', $assoc = false) {
        $data = json_decode($data, $assoc);
        if ($data && (is_object($data)) || (is_array($data) && !empty(current($data)))) {
            return $data;
        }
        return false;
    }

}

